﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ExtendedReflection.Metadata;
using NLog.Win32.Targets;
using NLog.Config;
using NLog.Targets;
using NLog;
using DUCover.Static;
using DUCover.Persistence;

namespace DUCover.Core
{
    /// <summary>
    /// A main program for DUCover that sets up all initialization and store all 
    /// static instances used in the tool
    /// </summary>
    public static class DUCoverMain
    {
        static bool bLoggerInitialized = false;

        /// <summary>
        /// Initializes DUCover.
        /// </summary>
        public static void Initialize(AssemblyEx assembly)
        {
            if (!bLoggerInitialized)
            {
                InitializeLogger();
                bLoggerInitialized = true;
            }

            //Check whether intialization information is required for this assembly
            var shortname = assembly.ShortName;
            if (DUCoverConstants.SystemAssemblies.Contains(shortname))
                return;

            DeclEntityCollector.CollectAllDeclEntitiesInAssembly(assembly);
        }

        /// <summary>
        /// Includes functionality for handling terminating actions
        /// </summary>
        public static void Terminate()
        {
            AllDeclEntity ade = AllDeclEntity.GetInstance();
            MyFileWriter.DumpAllDeclEntity(ade);
        }

        /// <summary>
        /// Initializes logging framework
        /// </summary>
        private static void InitializeLogger()
        {            
            LoggingConfiguration config = new LoggingConfiguration();

            // Create targets and add them to the configuration
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);            
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss}: ${message}";

            // set the file
            fileTarget.FileName = DUCoverConstants.LogFileName;
            fileTarget.Layout = "${date:format=HH\\:MM\\:ss}: ${message}";            
            fileTarget.DeleteOldFileOnStartup = true;

            // Step 4. Define rules
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);        
            
            LogManager.Configuration = config;            
        }
    }
}
